<?php

namespace App\Service\Pay;

use App\Models\User;
use App\Services\TronService;
use Exception;
use App\Jobs\Orderstate;

class Trc20usdtPayService extends PayService implements Pay
{


    //充值
    public function recharge($attach = [])
    {

        return false;

    }

    public function withdrawal($attach = [])
    {
        try {
            $user = User::query()->where('id',$this->order->user_id)->first();
            if(!$user){
                $this->withdrawalCallback([], ['msg' => '收款地址不存在'], '', false);
            }

            if(!isset($attach['key']) || empty($attach['key'])){
                $this->withdrawalCallback([], ['msg' => 'KEY不存在'], '', false);
            }

            if($user->type == 'trc'){
                $result = app(TronService::class)->transfer($user->address, (float)$this->order->actual_amount ,$this->merchant, $attach['key']);

                if($result){
                    $state = true;
                    Orderstate::dispatch($this->order)->delay(60)->onQueue(config('jobQueue.default'));
                }else{
                    $state = false;
                }
                $this->withdrawalCallback([], [$result], $result, $state);
                $this->order->save();
            }else{
                $this->withdrawalCallback([], ['msg' => '该通道只支持TRC'], '', false);
            }
        } catch (Exception $exception) {
            $this->withdrawalCallback([], ['msg' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine()], '', false);
        }
    }


    /**
     * 签名
     * @param $data
     * @param $secret
     * @return string
     */
    protected function sign($data, $secret): string
    {
        ksort($data);
        $str = '';
        foreach ($data as $key => $val) {
            if ($val != null) {
                $str .= $key . '=' . $val . '&';
            }
        }
        return strtolower(md5($str . 'key=' . $secret));
    }

    /**
     * 验签
     * @param array $params
     * @param string $type
     * @return bool
     */
    public function checkSign(array $params, string $type): bool
    {
        $sign = $params['sign'];
        // 验证签名参数是否正确
        unset($params['sign'], $params['signType'], $params['merRetMsg']);
        return $sign == $this->sign($params, $type == 'pay' ? $this->pay_key : $this->withdrawal_key);
    }

}
